package server.catalina.core;

import java.io.*;

/**
 * @ProjectName: MinicatV4.0
 * @Title: LagouClassLoader
 * @Package: server
 * @Description: ClassLoader
 * @author: Ian
 * @date: 1/18/2021 10:02 AM
 * @version: V1.0.0
 * @Copyright: 2021 www.lagou.com Inc. All rights reserved.
 */
public class LagouClassLoader extends ClassLoader {
    private String classPath;

    public LagouClassLoader(String classPath) {
        this.classPath = classPath;
    }

    public LagouClassLoader() {
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return super.loadClass(name);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = getData(name);
        if (classData == null) {
            throw new ClassNotFoundException();
        } else {
            System.out.println("当前类加载器:" + this.getClass().getClassLoader().toString());
            return defineClass(name, classData, 0, classData.length);
        }
    }

    private byte[] getData(String name) {
        String path = classPath + File.separatorChar + name.replace('.', File.separatorChar) + ".class";
        try {
            InputStream is = new FileInputStream(path);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num = 0;
            while ((num = is.read(buffer)) != -1) {
                stream.write(buffer, 0, num);
            }
            return stream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
